import { defineStore } from "pinia";
import { ElMessage } from "element-plus";
import { UserProfile, UserAccount } from "@/types/login";
import {
  generateQRCode,
  generateQRCodeKey,
  chkQRLoginState,
  getLoginStatus,
} from "@/api/login";

const useLoginStore = defineStore("login", {
  state: () => ({
    QRKey: "",
    qrimg: "",
    qrurl: "",
    loginType: 0, // 0扫码 1手机
    shouldRefresh: false,
    cookie: localStorage.getItem("appCookie") || "",
    userData: null as UserProfile | null,
    accountData: null as UserAccount | null,
    timer: "" as any,
    loginSuccess: false,
  }),
  actions: {
    init(cb?: () => void) {
      if (this.cookie !== "") {
        this.getLoginStatusByCookie().then(() => {
          if (typeof cb === "function") {
            cb();
          }
        });
      }
    },
    async getLoginStatusByCookie() {
      const res = await getLoginStatus(this.cookie);
      if (res.data && res.data.code === 200) {
        this.userData = res.data.profile;
        this.accountData = res.data.account;
        this.loginSuccess = true;
      }
    },
    async fetchQRKey() {
      try {
        const res = await generateQRCodeKey();
        if (res.code === 200 && res.data && res.data.unikey) {
          const key = res.data.unikey;
          this.QRKey = key;
          const QRCodeData = await generateQRCode(key);
          if (QRCodeData.code === 200) {
            this.qrimg = QRCodeData.data.qrimg;
            this.qrurl = QRCodeData.data.qrurl;
          }
        }
      } catch (err) {
        console.error(err);
      }
    },
    async refreshQRCode() {
      try {
        const QRCodeData = await generateQRCode(this.QRKey);
        if (QRCodeData.code === 200) {
          this.qrimg = QRCodeData.data.qrimg;
          this.qrurl = QRCodeData.data.qrurl;
          this.shouldRefresh = false;
        }
      } catch (err) {
        console.error(err);
      }
    },
    startLoopCheckQRLoginState() {
      this.timer = setInterval(async () => {
        const res = await chkQRLoginState(this.QRKey);

        if (res.code === 800) {
          this.shouldRefresh = true;
          clearInterval(this.timer);
        }
        if (res.code === 803) {
          // 这一步会返回cookie
          clearInterval(this.timer);

          localStorage.setItem("appToken", res.token);
          localStorage.setItem("appCookie", res.cookie);
          // this.getLoginStatusByCookie();
          ElMessage({
            type: "success",
            message: "登录成功",
            onClose: () => {
              window.location.reload();
            },
          });
        }
      }, 5000);
    },
    stopLoopCheckQRLoginState() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = false;
      }
    },
  },
});

export default useLoginStore;
